﻿
using Microsoft.Extensions.DependencyInjection;
using MS.Core.Helper;
using SqlSugar;
using System.Reflection;


namespace ReportDesignerServer
{
    public static class IocServiceSetup
    {
        /// <summary>
        /// NetCore自带容器中注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void AddIocSetup(this IServiceCollection services)
        {
            #region 报表类单个注入
            //注入 token 生成类
            services.AddTransient<TokenHelper>();


            #endregion

            #region 依赖注入
            //所有引用dll查找
            //Assembly.GetExecutingAssembly()
            var referencedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            var types = referencedAssemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(t => t.Namespace != null && t.Namespace.Contains("ReportDesignerServer"))
                .Where(t => t.Name.EndsWith("Repository") || t.Name.EndsWith("Service")).ToArray();
            //当前程序集下，查找类注入容器
            //Assembly assembly = Assembly.GetExecutingAssembly();
            // Type[] types = assembly.GetTypes().Where(t => t.Name.EndsWith("Repository") || t.Name.EndsWith("Service")).ToArray();
            var implementTypes = types.Where(x => x.IsClass).ToArray();
            var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
            foreach (var implementType in implementTypes)
            {
                if (implementType.Name.EndsWith("Service"))
                {
                    services.AddScoped(implementType);
                }
                else
                {
                    var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                    if (interfaceType != null)
                        services.AddScoped(interfaceType, implementType);
                }
            }
            #endregion
        }
    }
}
